import useTablePage from "@/hooks/crud/useTablePage";
import useTableRequest from "@/hooks/crud/useTableRequest";
import useTableSearch from "@/hooks/crud/useTableSearch";
import useTableSelection from "@/hooks/crud/useTableSelection";
import useTablePermission from "@/hooks/crud/useTablePermission";
import useTableCUD from "@/hooks/crud/useTableCUD";
import type { Ref } from "vue";
import type { AxiosPromise } from "axios";
import type { CudOptions } from "./useTableCUD";
import type { requestOptionTy } from "./useTableRequest";
import type { CrudResultType } from "./type";

interface CrudOptionsTy<P> {
  // table 请求接口方法
  fetch: ((current: number, size: number, params?: object) => P) | null;
  // 请求table数据相关配置
  requestOption?: requestOptionTy;
  cudOptions: Omit<CudOptions, "page">;
}
export default function <T extends Promise<BaseResType>>(
  options: CrudOptionsTy<T>
): any {
  if (!options) {
    console.warn("请传入必要配置项！");
    return;
  }
  // table ref
  const tableRef: Ref<any> = ref();
  // table form
  const form: Ref<object> = ref({});
  // crud
  const _ = options;

  const { currentChange, sizeChange, page } = useTablePage();
  const { onLoad, data, loading } = useTableRequest<T>(
    _.fetch,
    _?.requestOption
  );
  const { searchChange, searchReset, query } = useTableSearch(page, onLoad);
  const { permission, roles } = useTablePermission();
  const { selectionChange, selectionList, ids } = useTableSelection();
  const cudOption: CudOptions = {
    tableRequest: onLoad,
    ..._?.cudOptions,
    page,
  };
  const { rowDel, rowSave, rowUpdate } = useTableCUD(cudOption);
  return {
    tableRef,
    form,
    currentChange,
    sizeChange,
    page,
    onLoad,
    data,
    loading,
    searchChange,
    searchReset,
    query,
    permission,
    roles,
    selectionChange,
    selectionList,
    ids,
    rowDel,
    rowSave,
    rowUpdate,
  };
}
